package com.tanguy.driver.net.socket

import android.support.v7.app.AppCompatActivity
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.tanguy.driver.App.Companion.app
import com.tanguy.driver.Const
import com.tanguy.driver.bean.socket.NewOrder
import com.tanguy.driver.interfaces.RequestHelper
import com.tanguy.driver.net.http.HttpManager
import com.tanguy.driver.ui.window.MessageWindow
import com.tanguy.driver.ui.window.NewOrderWindow
import com.tanguy.driver.utlis.RxBus
import com.tanguy.driver.utlis.StackManager
import com.tanguy.driver.utlis.extend.getDeviceId
import com.tanguy.driver.utlis.extend.loge
import com.tanguy.driver.utlis.extend.requestSucceed
import com.tanguy.driver.utlis.extend.showPopupWindow
import org.json.JSONObject

/**
 * Created by dab on 2017/11/27 0027 11:20
 * Socket通讯管理类
 */

object SocketManager {
var canUpLocation=true
    /**
     * 心跳
     */
    fun ping() {
        val jsonObject = JsonObject()
        jsonObject.addProperty("id", app.userId)
        jsonObject.addProperty("role", 2)
        jsonObject.addProperty("method", Const.SocketType.OK)
        jsonObject.addProperty("token", app.getDeviceId())
        app.sendMassage(jsonObject.toString())
    }

    /**
     * 司机上传位置
     */
    fun upLocation(lon: Double, lat: Double, citycode: String) {
        if (!canUpLocation)return
        canUpLocation=false
        val jsonObject = JsonObject()
        jsonObject.addProperty("id", app.userId)
        jsonObject.addProperty("role", 2)
        jsonObject.addProperty("method", Const.SocketType.LOTICO)
        jsonObject.addProperty("token", app.getDeviceId())
        jsonObject.addProperty("lon", lon)
        jsonObject.addProperty("lat", lat)
        jsonObject.addProperty("citycode", citycode)
        app.sendMassage(jsonObject.toString())
    }

    /**
     * 解析服务端发送过来的json
     */
    fun parseJson(json: String) {
        val jsonObject = JSONObject(json)
        val code = jsonObject.get("code")?.toString()
        if (code.isNullOrEmpty() || code != "0") return
        val method = jsonObject.get("method")?.toString()
        if (method.isNullOrEmpty()) return
        val con = jsonObject.get("con")?.toString()
        dispense(method!!, con)
        //日志  过滤掉经常发的
        if (method == Const.SocketType.OK //心跳
                || method == Const.SocketType.DRIVER_LINEUP //在排队区域
                || method == Const.SocketType.LINEUP_ZHONG //排队号码
                || method == Const.SocketType.LONCTION //上传成功
                ) return
        loge(json)
    }

    /**
     * 分发消息
     */
    private fun dispense(method: String, con: String?) {
        when (method) {
            Const.SocketType.OK -> return
            Const.SocketType.LONCTION -> canUpLocation=true
            Const.SocketType.NEW_ORDERALLDRIVER -> newOrder(con) //新订单推送
            Const.SocketType.DRIVER_LINEUP -> queueUp(con) //进入可排队区域标识
            Const.SocketType.LINEUP_ZHONG -> queueChange(con)//排队号码变化
            Const.SocketType.PAIORDER_DRIVER -> allot(con)//派单推送
            Const.SocketType.USER_CENLE_ORDER -> userCancel(con)//用户取消订单
            else -> {
                loge(method + con)
            }

        }


    }

    /**
     * 用户取消了订单
     */
    private fun userCancel(con: String?) {
        if (con.isNullOrEmpty()) return
        val jsonObject = JSONObject(con)
        val orderId = jsonObject.getInt("orderId")
        RxBus.instance.post(Const.RxType.REFRESH_MAIN_ORDER, orderId.toString())
    }

    /**
     * 派单
     */
    private fun allot(con: String?) {
        if (con.isNullOrEmpty()) return
        val jsonObject = JSONObject(con)
        val orderId = jsonObject.getInt("orderId")
        RxBus.instance.post(Const.RxType.ALLOT, orderId)
    }

    /**
     * 排队号码变化
     */
    private fun queueChange(con: String?) {
        if (con.isNullOrEmpty()) return
        val jsonObject = JSONObject(con)
        val num = jsonObject.getInt("num")
        app.isQueue = true
        RxBus.instance.post(Const.RxType.QUEUE_CHANGE, num)
        RxBus.instance.post(Const.RxType.CAN_QUEUE, true)
    }

    /**
     * 进入可排队区域标识
     */
    private fun queueUp(con: String?) {
        if (con.isNullOrEmpty()) return
        val jsonObject = JSONObject(con)
        val id = jsonObject.getInt("id")
        val type = jsonObject.getInt("type")
        val code = jsonObject.getString("code")
        app.code = code
        if (app.lastAreaID != id) {     //排队区域变了,弹窗提示
            val currentActivity = StackManager.currentActivity()
            currentActivity.showPopupWindow(MessageWindow(currentActivity, "你已进入可排队派单区域,\n是否愿意参与排队?", true) {
                if (it) {
                    HttpManager.lineup(type.toString(), id.toString())
                            .requestSucceed(currentActivity as RequestHelper) {
                                when (it.get("type").asInt) {
                                    1 -> currentActivity.showToast("当前不符合排队规则")
                                    2 -> currentActivity.showToast("当前不在排队区域内")
                                    3 -> {
                                        currentActivity.showToast("排队成功")
                                        val num = it.get("num").asInt
                                        app.isQueue = true
                                        RxBus.instance.post(Const.RxType.QUEUE_CHANGE, num)
                                    }
                                }
                            }
                }

            }.setBtnText("不参与", "参与排队")
            )
        }
        app.lastAreaID = id
        app.lastAreaType = type
        RxBus.instance.post(Const.RxType.CAN_QUEUE, true)
    }

    /**
     * 新订单推送
     */
    private fun newOrder(con: String?) {
        if (con.isNullOrEmpty()) return
        val newOrder = Gson().fromJson<NewOrder>(con, NewOrder::class.java)
//                RxBus.instance.post(Const.SocketType.NEW_ORDERALLDRIVER, newOrder)
        val currentActivity = StackManager.currentActivity()
        currentActivity.showPopupWindow(NewOrderWindow(currentActivity as AppCompatActivity, newOrder) {
            val orderId = it.orderId.toString()
            HttpManager.grabOrder(orderId)
                    .requestSucceed(currentActivity as RequestHelper) {
                        RxBus.instance.post(Const.RxType.REFRESH_MAIN_ORDER, orderId)
                        loge(it)
                        currentActivity.showToast("抢到${it.name}的订单")
                    }
        })
    }

}
